﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Net.Http;
using System.IO;
using System.Threading.Tasks;

namespace ArgusPCLib.Xml
{
	public class UpdateInfoXml : UpdateInfo
	{
		public UpdateInfoXml()
			: base() { }
		public UpdateInfoXml(string buildName, ReleaseStatus releaseStatus, Version buildVersion, string homepageLink, string downloadLink, string directDownloadLink, int crc32, string description)
			: base(buildName, releaseStatus, buildVersion, homepageLink, downloadLink, directDownloadLink, crc32, description) { }

		protected virtual string XmlRootName { get { return "UpdateInfo"; } }

		public async Task SaveAsync(Stream stream)
		{
			using (Serializer seri = Serializer.FromStream(stream, this.XmlRootName))
			{
				seri.Serialize(this);
			}
		}

		public static async Task<UpdateInfoXml> LoadAsync(Stream stream)
		{
			return await UpdateInfoXml.LoadAsync<UpdateInfoXml>(stream);
		}

		public static async Task<T> LoadAsync<T>(Stream stream) where T:UpdateInfoXml, new()
		{
			T updateInfo = new T();
			using (Deserializer deseri = Deserializer.FromStream(stream))
			{
				if (deseri.RootName != updateInfo.XmlRootName)
					return null;
				return deseri.Deserialize() as T;
			}
		}

		public static async Task<UpdateInfoXml> DownloadAsync(Uri source)
		{
			return await UpdateInfoXml.DownloadAsync<UpdateInfoXml>(source);
		}

		public static async Task<T> DownloadAsync<T>(Uri source) where T:UpdateInfoXml, new()
		{
			using (HttpClient httpClient = new HttpClient())
			{
				using (Stream stream = await httpClient.GetStreamAsync(source))
				{
					return await UpdateInfoXml.LoadAsync<T>(stream);
				}
			}
		}
	}
}
